package ua.maxicash.service;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ua.maxicash.vo.Employer;
import ua.maxicash.vo.SystemUser;
import ua.maxicash.vo.Worker;

import java.util.ArrayList;
import java.util.Collection;

@Service("assembler")
public class Assembler {

	@Transactional(readOnly = true)
	User buildUserFromUserEntity(SystemUser systemUser) {

		String username = systemUser.getEmail();
		String password = systemUser.getPassword();

		boolean enabled = systemUser.isEnabled();
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		if (systemUser instanceof Worker)
			authorities.add(new GrantedAuthorityImpl("ROLE_WORKER"));
		if (systemUser instanceof Employer)
			authorities.add(new GrantedAuthorityImpl("ROLE_EMPLOYER"));

		User user = new User(username, password, enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, authorities);
		return user;
	}
}
